<!DOCTYPE html>
<html>
<head>
    <title>会员训练内容录入</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/badge.css') }}">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <h2>鹿鹿泽健身工作室会员训练日志</h2>        
        <h3><image src="../static/ico/客户.svg" class="ico"></image> 会员编码及姓名</h3>
            <input type="text" id="nameInput" placeholder="请输入会员姓名" oninput="handleInput()" style="margin-bottom: 8px;width:120px;">
            <div id='stageBlock' style="text-align: center;width:100px;background-color: rgb(238, 241, 238);border: 1px snow solid; border-radius: 12px;margin:8px 0;padding:10px;">
                <div id="stage"></div>       
                <div id="offsetAmount"></div>         
                <div id="badge"></div>
            </div>
        <div id="cusNameList" class="cus-list-result" style="display:none;"></div>
        <div id="cusClsTkn" class="cusClsTkn"></div>   
        <hr>   
    <div id="trainSummary" style="margin-bottom: 16px;"></div>
    <div id="BasicInfo" style="padding:10px;border-radius: 10px;">   
        <h2>上课基本信息</h2> 
        <div id="insSelectBlock">
            <h3>上课教练</h3>
            <select id="insSelect"></select>
        </div>        

        <h3>课程类型</h3>
        <select id="buyType" onchange="getValidClass();generateClsNameSelect();">
        </select>

        <h3>课程名称</h3>
        <select id="buyClsName" onchange="getValidClass();">
        </select>

        <div id="cardId" class="form-row" ><h4 style="margin-top:20px;margin-left:0px;">关联卡号：</h4><select id='cardIdStr'></select><span id="clsRemain"></span></div>
        <div >有效上课时段：<span id="validTime"></span></div> 
        <div id="validClassEndTime"></div>
        <div id="errBuyType" class="inline2"></div>
        <div id="continueBuyClsInfo"></div>

        <div id="date">
            <h3> 上课日期和时间</h3>
                <form>
                    <label for="datetime"></label>
                    <input type="datetime-local" id="datetime" name="datetime" onchange="getValidClass()">
                    <br>
                </form>
        </div>    

        <div>
            <h3>上课时长</h3>
            <label for="clsLong"></label>
            <select id="clsLong" style="width:50px;">
                <option value="1" selected>1</option>
                <option value="2">2</option>
            </select>
            小时
        </div>
        <h3>备注</h3>
        <textarea id="basic_cls_comment"></textarea>
        <!-- <input type="text" id="basic_cls_comment"> -->
    </div>


    <div id="allTrainContents" style="display:none;">
        <div style="margin-bottom:10px;"></div>
        <hr>
        <h2>训练内容</h2>    

        <div id="trainItems">
            <div id="trainItemDetail-0" name="trainItemDetail">
                <h3 id="trainRecCount-0" class="train-reccount">训练记录  第1条</h3>
                <div id="inputTypeBox-0" class="form-row">
                    <h4 style="width:70px;">输入方式</h4>
                    <select id='inputType-0' onchange='showInputBox(this.id);showInputDetailBox(this.id.split("-")[1]);clearTrainItemInput(this.id.split("-")[1]);'>
                        <option value='分类输入'>分类输入</option>
                        <option value='模糊输入'>模糊输入</option>
                    </select>
                </div>
                <!-- <h4>训练项目</h4> -->
                <div id="inputByCatBox-0" class="form-row" style="flex-direction: column;justify-content: start;align-items: start;border:solid 1px rgb(220, 232, 255);">
                    <div style="background-color: aliceblue;width: 100%;padding-bottom:10px;">
                        <h4 style="width:70px;">训练形式</h4>
                        <label for="formBox-0"></label>
                        <div id="formBox-0" class="dynamic-radio" style="margin-left:18px;"></div>     
                    </div>
                    <div style="background-color: rgb(255, 248, 237);width: 100%;padding-bottom:10px;">
                        <h4 style="width:70px;">目标肌群</h4>
                        <div id="muscleBox-0" class="dynamic-radio" style="margin-left:18px;"></div>                    
                    </div>
                </div>

                <div id='inputByInputBox-0' class="form-row" style="display:none;flex-direction: column;justify-content: start;align-items: start;">
                    <div style="width:100%;border:solid 1px rgb(220, 232, 255);padding-bottom: 10px;background-color: rgb(241, 245, 249);">
                        <h4 style="width:140px;">输入训练项目名称</h4><input id="inputByInput-0" oninput="handleTrainNameInput(this.id);" style="margin-left:10px;">
                    </div>
                    <div id="inputByInputTrainList-0" class="train-list5" style="display:none"></div>
                </div>


                <div id="nonOxy-0" style="display: none;" class="nonOxy">
                    <h4 style="color:rgb(157, 76, 76)">力量/综合/拉伸训练</h4>
                    <input id="nonOxyName-0" oninput="handleNonOxyNameInput(this)" onclick="handleNonOxyNameInput(this)" style="font-size:18px;color:brown;">
                    <div id="nonOxyTrainList-0" class="train-list3" style="display:none"></div>
                        <h4>重量
                        <label for="nonOxyWt-0"></label>
                        <select id="nonOxyWt-0">
                            <option value=0>0</option>
                            <option value=0.5>0.5</option>
                            <option value=1>1</option>
                            <option value=1.5>1.5</option>
                            <option value=2>2</option>
                            <option value=2.5>2.5</option>                    
                            <option value=5>5</option>                    
                            <option value=7.5>7.5</option>
                            <option value=10>10</option>
                            <option value=12.5>12.5</option>
                            <option value=15>15</option>
                            <option value=17.5>17.5</option>
                            <option value=20>20</option>
                            <option value=22.5>22.5</option>
                            <option value=25>25</option>
                            <option value=30>30</option>
                            <option value=35>35</option>
                            <option value=40>40</option>
                            <option value=45>45</option>
                            <option value=50>50</option>
                            <option value=55>55</option>
                            <option value=60>60</option>
                            <option value=65>65</option>
                            <option value=70>70</option>
                            <option value=75>75</option>
                            <option value=80>80</option>
                            <option value=85>85</option>
                            <option value=90>90</option>
                            <option value=95>95</option>
                            <option value=100>100</option>

                        </select>
                        Kg</h4>
                        
                        <h4>次数
                        <label for="nonOxyNum-0"></label>
                        <select id="nonOxyNum-0">
                            <option value=1>1</option>
                            <option value=2>2</option>
                            <option value=3>3</option>
                            <option value=4>4</option>
                            <option value=5>5</option>                    
                            <option value=6>6</option>                    
                            <option value=7>7</option>
                            <option value=8>8</option>
                            <option value=9>9</option>
                            <option value=10>10</option>
                            <option value=11>11</option>
                            <option value=12>12</option>
                            <option value=13>13</option>
                            <option value=14>14</option>
                            <option value=15>15</option>
                            <option value=16>16</option>
                            <option value=17>17</option>
                            <option value=18>18</option>
                            <option value=19>19</option>
                            <option value=20>20</option>
                            <option value=21>21</option>
                            <option value=22>22</option>
                            <option value=23>23</option>
                            <option value=24>24</option>
                            <option value=25>25</option>
                            <option value=26>26</option>
                            <option value=27>27</option>
                            <option value=28>28</option>
                            <option value=29>29</option>
                            <option value=30>30</option>
                        </select>次
                        </h4>

                        <h4>距离
                            <input id="nonOxyDis-0" style="width: 40px;" type="number" min="0">米</h4>

                        <h4>组数
                        <select id="nonOxyGroup-0">
                            <option value=1>1</option>
                            <option value=2>2</option>
                            <option value=3>3</option>
                            <option value=4>4</option>
                            <option value=5>5</option>                    
                            <option value=6>6</option>                    
                            <option value=7>7</option>
                            <option value=8>8</option>
                            <option value=9>9</option>
                            <option value=10>10</option>
                        </select>
                        组</h4>
                </div>   
                
                <div id="oxy-0" style="display: none;" class="oxy">
                    <h4 style="color:rgb(75, 134, 84)">有氧训练</h4>
                    <input id="oxyName-0" oninput="handleOxyNameInput(this)" onclick="handleOxyNameInput(this)" style="font-size:18px;color:rgb(26, 122, 58);">
                    <div id="oxyTrainList-0" class="train-list4" style="display:none"></div>
                        <h4>有氧训练时间 
                        <input id="oxyTime-0" style="width: 50px;" type="number" min="0"> 分</h4>

                    <h4>组数<span style="width:10px;"></span>
                    <select id="oxyGroup-0">
                        <option value=1>1</option>
                        <option value=2>2</option>
                        <option value=3>3</option>
                        <option value=4>4</option>
                        <option value=5>5</option>                    
                        <option value=6>6</option>                    
                        <option value=7>7</option>
                        <option value=8>8</option>
                        <option value=9>9</option>
                        <option value=10>10</option>
                    </select>
                    <span style="width:20px;"></span>组
                    </h4>
                </div>                
                <hr>
            </div>
            
        </div>

        <button id="appendTrainButton" onclick="copyTrain()">添加一条训练记录</button>
        <div>
            <h4>热量消耗
            <input  type="number" id="calories" style="width:50px;" min="0"> Kcal</h4>
            <h4>上课点评</h4>
            <!-- <input type="text" id="trainComment" style="height:80px;"> -->
            <textarea id="trainComment" style="height:80px;"></textarea>
            <div></div>
        </div>
        <hr>
        <div id="processingModel" style="display: none;">
            <!-- 这里是弹出框的内容 -->
            <p style="color:rgb(40, 57, 78);font-size:30px;">正在处理中，请稍候...</p>
        </div>
        <button id="tempSaveButton" onclick="tempSave()">暂存</button>
        <button id="editButton" onclick="enableEdit()">返回修改</button>
        <button id="submit" onclick="submit()">提交</button>
    </div>
    
    <!-- <button id="submit" onclick="getTrainItems()">获取训练数据</button> -->
    <script src="../static/js/common.js"></script> 
    <script src="../static/js/clsMsgAlert.js"></script> 
    <script>
        let cus_list;
        let ins_list;
        let train_list;
        let valid_class;
        let classAndBodyHistory;
        let copyCount=0;
        let deleteCount=0;
        let blockOrder=1;
        let insName;
        let insId;
        let insRole;
        let insIdReload;
        let tmplt_info;
        let train_summary;
        let currentClsLongValue;
        let cusTotalAmout=0;
        // 在页面加载完成后，将返回修改按钮和性别输入框设置为不可见
        document.addEventListener("DOMContentLoaded", function(){
            // loginCheck();
            insInfo=hideInsSelectBlockAndGetInsInfo('insSelectBlock');
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];
            
            document.getElementById("editButton").style.display = "none";
            document.getElementById("submit").setAttribute("disabled", true);
            selectToday(id='datetime',format='dateTime');

            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    tmplt_info=data;
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('get data from template file:',data);
                generateBuyTypeList(data);
                generateClsNameSelect(data);
                  })
                .catch(error => console.error('Error:', error));

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log(data);
                cus_list=data;
                  })
                .catch(error => console.error('Error:', error));

                          


            fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('ins list:',data);
                ins_list=data.ins_list;
                generateInsList(data.ins_list,'insSelect');
                 })
                .catch(error => console.error('Error:', error));

                fetch('/get_train_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('all train items:',data);
                train_list=data;
                initForm(data);
                initMuscle(data);
                })
                .catch(error => console.error('Error:', error));

           console.log('dom loaded:',insInfo)

        //获取会员等级配置
           getCusStageConfig();

        //隐藏会员等级
        document.getElementById('stageBlock').style.display='none';

           const clsLongElement=document.getElementById('clsLong');
           clsLongElement.addEventListener('change',function(){
            currentClsLongValue = document.getElementById('clsLong').value;
            console.log('currentClsLongValue:',document.getElementById('clsLong').value);
           });
        });

        function getCusBuySum(name){
        return fetch(`/get_cus_buy_sum?cus_id=${encodeURIComponent(name.slice(0,7))}`)
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){
                    console.log('get cus buy sum data:',data);
                    return parseFloat(data.data[0]['total_amount']);
                } else {
                    throw new Error(data.msg || '获取会员总购课金额失败');
                }                     
            })
            .catch(error=>{
                console.log('获取会员总购课金额错误：',error);
                throw error;
            });  
        }             
        

         function showCusStage(totalAmount){
            const ranges = Object.keys(cusStageConfig);
            let range = null;
            for (const rangeKey of ranges) {
            const [min, max] = rangeKey.split('-').map(Number);
            if (Math.round(totalAmount/10) >= Math.round(min/10) && Math.round(totalAmount/10) < Math.round(max/10)) {
                range = cusStageConfig[rangeKey];
                console.log('所在的range：',range);
                break;
            }
            }

            // 根据会员等级显示相应的勋章
            let badgeClass = '';
            let badgeText = range.name;
            
            switch(range.name) {
                case '心动行动':
                    badgeClass = 'badge badge-bronze';
                    break;
                case '渐入佳境':
                    badgeClass = 'badge badge-silver';
                    break;
                case '身体力行':
                    badgeClass = 'badge badge-gold';
                    break;
                case '知行合一':
                    badgeClass = 'badge badge-platinum badge-glow';
                    break;
                default:
                    badgeClass = 'badge badge-bronze';
            }

            document.getElementById(`stage`).innerHTML=`<span style='font-size:10px;font-weight:bold;'>${range.star} @ ${Math.round(totalAmount/10)}分</span>`;
            document.getElementById(`stage`).style.fontSize='14px';
            if(range.star && ['二星会员','三星会员','四星会员'].includes(range.star)){
                document.getElementById(`stage`).innerHTML=`<div style="line-height:1.2;margin:0;padding:0;text-align:center;"><div style='font-size:10px;font-weight:bold;'>${range.star} @ ${Math.round(totalAmount/10)}分</div><div style="font-size:10px;margin:0;padding:2px;color:#ff6b35;font-weight:bold;">购课即享优惠</div></div>`;
            }
            document.getElementById(`badge`).innerHTML=`<div class="${badgeClass}" style='margin-top:8px;'>${badgeText}勋章</div>`;
            document.getElementById('offsetAmount').innerHTML=`<div style='font-size:10px;'>单次消费满${range.offset_limit}元</div><div style='font-size:10px;'>立减${range.offset_amount}元</div>`;

        }


        function getCusStageConfig(){
            fetch('/get_cus_stage_config', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {                
                cusStageConfig=data.stage_config;
                console.log('cusStageConfig list:',cusStageConfig);
                  })
                .catch(error => console.error('Error:', error)); 

        }


        function generateClsNameSelect(data){     
            if(!data){
                data=tmplt_info;
            }                
            const buyType=document.getElementById('buyType').value;
            if(buyType===''){
                buyType='限时课程';
            }

            // console.log('clsNameData:',data['cls_type_name_dic'][buyType])   
            const buyClsName=document.getElementById('buyClsName');
            buyClsName.innerHTML='';
            data['cls_type_name_dic'][buyType].forEach(clsName=>{           
                //私教课程上课，课程类型不显示小团课。     
                if(clsName!=='小团课'){
                    const clsNameOpt=document.createElement('option');
                    clsNameOpt.value=clsName;
                    clsNameOpt.textContent=clsName;
                    buyClsName.appendChild(clsNameOpt);
                }

            });
        }

        async function handleInput() {
            // 获取输入框中的值
            const searchTerm = document.getElementById("nameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusNameList");
            const cusClsTkn=document.getElementById('cusClsTkn')
            const allTrainContents=document.getElementById('allTrainContents');
            allTrainContents.style.display='none';

            const today=dateToStringGmt(new Date(),'date');

            //隐藏会员等级
            //隐藏会员等级
            document.getElementById('stageBlock').style.display='none';

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.textContent = name;

                    // 添加点击事件监听器,点击名字时执行。
                    listItem.addEventListener("click", async function() {
                        //显示会员等级
                        document.getElementById('stageBlock').style.display='block';
                        
                        try{
                            const totalAmount = await getCusBuySum(name);
                            cusTotalAmount = totalAmount;
                            console.log('客户总购课金额：',totalAmount);
                            showCusStage(cusTotalAmount);

                        }catch(error){
                            console.error('获取客户购课总金额错误',error)
                            cusTotalAmout=0
                        }

                        const trainSummary=document.getElementById('trainSummary');
                        trainSummary.textContent='';
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("nameInput").value = name;

                        // 点击后隐藏名字列表框
                        resultList.style.display = "none";
                        // 点击后隐藏上课及围度信息
                        cusClsTkn.style.display='none';

                        fetch('/get_cus_info',{
                            method:'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body:JSON.stringify({'selected_name':name,'today':today})
                            })
                        .then(response=>response.json())
                        .then(class_histrory_body_data=>{
                            // console.log('classAndBodyHistory:',class_histrory_body_data);
                            classAndBodyHistory=class_histrory_body_data;
                            //报告课程时返回剩余节数供alert
                            reportClassTaken();                    
                            getValidClass(name);
                            // console.log('get valid cards')
                            // getValidCards(name);
                            
                        })
                        .catch(error=>{
                            console.log('获取既往上课错误：',error)
                        });                 
                        
                        fetch('/get_train_summary', {
                            method: 'POST',
                            headers: {
                                    'Content-Type': 'application/json'
                                },
                            body:JSON.stringify({'cus_id_name':name})
                            })
                        .then(response => response.json())
                        .then(data => {
                        //将data赋值给块变量cus_list，供后面的handleInput使用
                            // console.log('train_summary:',data);
                            if(data['res']==='ok' && data['train_sum'].length>0){
                                showTrainSummary(data['train_sum']);
                            }

                        })
                        .catch(error => console.error('获取既往上课小结错误：', error));  
                        
                        
                        // 读取暂存的信息
                        let insIdPage;
                        if(insRole==='admin'){
                            insIdPage=document.getElementById('insSelect').value;
                        }else if(insRole==='ins'){
                            insIdPage=insId;
                        }else{
                            insIdPage=insId;
                        }
                        const tempSavePage=localStorage.getItem(insIdPage+'-'+name+'-html-clsinput');
                        if(tempSavePage){
                            const isConfirmed=confirm('该会员有一条暂存信息，是否需要读取？');
                            if(isConfirmed){
                                const allTrainContents=document.getElementById('allTrainContents');
                                allTrainContents.style.display='block';
                                document.documentElement.innerHTML=tempSavePage;
                                // console.log(insIdPage+'-'+name+'-cls_recs');
                                reFillTempSave(localStorage.getItem(insIdPage+'-'+name+'-cls_recs'));
                                selectToday('datetime','dateTime'); 
                                tempSave(show='no');
                            }                          
                        }
                        resultList.innerHTML = "";
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                }
            });        
        }

        function showTrainSummary(data){
            // console.log('train summary:',data)
            const trainSummary=document.getElementById('trainSummary');
            const table = document.createElement('table');
            table.classList.add('table-train-summary');

            const trainSummaryHeader=document.createElement('div');
            trainSummaryHeader.innerHTML=`
                <div style='color:#000086;'><h4>最近 ${data.length} 次训练记录</h4><div>

            `
            trainSummary.appendChild(trainSummaryHeader)

            // 创建表头行
            const headerRow = table.insertRow();
            
            for (const header of ['上课日期','上课内容','上课点评']) {
            const cell = headerRow.insertCell();
            cell.textContent = header;
            cell.style.fontSize='12px';
            }
            headerRow.classList.add('header-row-trainrec');

            // 创建表格内容
            for (let i = 0; i < Object.keys(data).length; i++) {
            const row = table.insertRow();
                for (let j=0;j<data[0].length;j++) {
                    const cell = row.insertCell();
                    if(j===0){
                        cell.textContent = dateToString(data[i][j],'date');    
                    }else{
                        cell.textContent = data[i][j];  
                    }
                                    
                }
            }
            trainSummary.appendChild(table);
        }

        function getValidCards(cusName){
            // console.log(cusName)
            fetch('/get_cards', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                    },
                body:JSON.stringify({'cus_id_name':cusName})
                })
                .then(response => response.json())
                .then(data => {
                    const validCards=data['valid_cards'];
                    const cardSel=document.getElementById('cards');
                    // console.log(validCards)
                    cardSel.textContent='';
                    //生成下拉的有效卡号供销课用
                    validCards.forEach((card,index)=>{
                        const option=document.createElement('option');
                        // console.log(card)
                        option.value=card[0];
                        option.text=card[0];                        
                        if(index===0){
                            option.selected=true;
                        }
                        cardSel.appendChild(option);                        
                    });
                    
                    
                    
                })
                .catch(error=>{                    
                    
                    console.error('获取有效卡错误',error)
                });
        }


        function formatTimeRange(timeStr) {
            // 1. 分割字符串，获取开始和结束时间
            const [start, end] = timeStr.split('-');
            
            // 2. 格式化时间（补全冒号）
            const formatTime = (time) => {
                const hours = time.slice(0, 2);  // 取前两位作为小时
                const minutes = time.slice(2);   // 取后两位作为分钟
                return `${hours}:${minutes}`;
            };
            
            // 3. 拼接成最终格式
            return `${formatTime(start)}-${formatTime(end)}`;
            }

           

        function getValidClass(cusName){
            const allTrainContents=document.getElementById('allTrainContents');
            const errBuyType=document.getElementById('errBuyType');
            const clsTakenTime=document.getElementById('datetime');
            const cardId=document.getElementById('cardId');
            const clsName=document.getElementById('buyClsName');
            const validTime=document.getElementById('validTime');
            const validTimeBlock=document.getElementById('validTimeBlock');
            const continueBuyClsInfo=document.getElementById('continueBuyClsInfo');
            continueBuyClsInfo.innerHTML='';

            try{
                document.getElementById('clsRemain').textContent='';
            }catch{

            }

            errBuyType.textContent='';
            validTime.textContent='-';
            validTime.style.color='#515539';
            // validTimeBlock.style.display='none';
            allTrainContents.style.display='none';
            cardId.style.display='none';

            if(!cusName || cusName===''){
                cusName=document.getElementById('nameInput').value;
            }
            const validClassEndTime=document.getElementById('validClassEndTime');
            validClassEndTime.textContent='';
            fetch('/get_cus_cls_infos', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                    },
                body:JSON.stringify({'cus_name':cusName,'cls_tkn_time':clsTakenTime.value})
                })
                .then(response => response.json())
                .then(data => {
                    console.log('cus buy and limit class infos:', data)
                    const clsType=document.getElementById('buyType').value;
                    const cardIdSel=document.getElementById('cardIdStr');
                    const classDate=document.getElementById('datetime').value.split('T')[0];
                    
                    if (clsType==='限时课程'){
                        const clsNameValue=clsName.value;
                        if(data['cus_cls_infos'][clsType].length>0){
                            for(i=0;i<data['cus_cls_infos'][clsType].length;i++){
                                const lmtCls=data['cus_cls_infos'][clsType][i];
                                // console.log('lmt lcs infos:',lmtCls,parseFloat(lmtCls[2]))
                                if(lmtCls[3]===clsNameValue){           
                                    //有效上课时段
                                    let validTimeStr;
                                    if(lmtCls[4]==='all_day'){                                
                                        document.getElementById('validTime').innerHTML='正常营业时间';
                                    }else{
                                        document.getElementById('validTime').innerHTML=`仅限 ${formatTimeRange(lmtCls[4])}`;
                                        document.getElementById('validTime').style.color='red';
                                    }
                                    
                                    
                                    const compareDate=new Date(classDate)-new Date(lmtCls[1]);
                                    const diffInDays = -1*Math.floor(compareDate / (1000 * 60 * 60 * 24));
                                    // console.log(diffInDays)
                                    const showDate=new Date(lmtCls[1]);
                                    showDate.setDate(showDate.getDate()-1);

                                    if(diffInDays>=5){
                                        validClassEndTime.innerHTML=`<span>本卡有效期至：${dateToString(showDate,'date')} </span>`;
                                    }
                                    if(diffInDays<5 && diffInDays >=0){
                                        validClassEndTime.innerHTML=`<span>本卡有效期至：${dateToString(showDate,'date')} </span>  <span style='color:#f23c1f;font-weight:bold;font-size:10px;'> 仅剩余${diffInDays}天，请提醒会员续课。</span>`;
                                    }
                                    if(diffInDays<0){
                                        validClassEndTime.innerHTML=``;
                                    }
                                    
                                    cardId.style.display='block';
                                    allTrainContents.style.display='block';
                                    cardIdSel.textContent='';
                                    errBuyType.textContent=''
                                    const opt=document.createElement('option');
                                    opt.value=lmtCls[0];
                                    opt.textContent=lmtCls[0];
                                    cardIdSel.append(opt);
                                    if(compareDate>0){
                                        allTrainContents.style.display='none';
                                        validClassEndTime.textContent='';
                                        cardId.style.display='none';
                                        errBuyType.textContent='无有效课程';
                                    }
                                    if(parseFloat(lmtCls[2])<=0){
                                        allTrainContents.style.display='none';
                                        validClassEndTime.textContent='';
                                        cardIdSel.textContent='';
                                        cardId.style.display='none';
                                        errBuyType.textContent='无有效课程';
                                    }

                                    showClsRemain([[lmtCls[0],lmtCls[1],lmtCls[2]]]);
                                    //查询续课的1899，是否达到连续续课3次
                                    getContinueClsRec(lmtCls[0]);
                                    break;
                                }else{
                                    allTrainContents.style.display='none';
                                    cardIdSel.textContent='';
                                    validClassEndTime.textContent='';
                                    cardId.style.display='none';
                                    errBuyType.textContent='无有效课程';
                                    break;
                                }
                            }
                            const eventCardId=new Event('change');
                            cardIdSel.dispatchEvent(eventCardId); 
                            if(cardIdSel.value){
                                    allTrainContents.style.display='block'; 
                                    cardId.style.display='block';
                                    errBuyType.textContent='';
                                
                            }else{
                                allTrainContents.style.display='none'; 
                                validClassEndTime.textContent='';
                                cardId.style.display='none';
                                errBuyType.textContent='无有效课程';
                            }

                        }else{
                            allTrainContents.style.display='none'; 
                            validClassEndTime.textContent='';
                            cardId.style.display='none';
                            errBuyType.textContent='无有效课程';
                        }
                                     
                    }

                    if (clsType==='常规课程'){
                        const clsName=document.getElementById('buyClsName').value;
                        cardId.style.display='block';
                        cardIdSel.textContent='';
                        errBuyType.textContent='';
                        for(i=0;i<data['cus_cls_infos'][clsType].length;i++){
                            const lmtCls=data['cus_cls_infos'][clsType][i];
                            // console.log(lmtCls)
                            if(lmtCls[3]===clsName){             
                                validTime.textContent=lmtCls[4]==='all_day'?'正常营业时间':formatTimeRange(lmtCls[4]);
                                if(lmtCls[4]==='all_day'){
                                    validTime.style.color='#515539';
                                }
                                           
                                const classDate=document.getElementById('datetime').value.split('T')[0];                                
                                // validClassEndTime.textContent=`本卡有效期至：${dateToString(lmtCls[1],'date')}`;                                
                                const opt=document.createElement('option');
                                opt.value=lmtCls[0];
                                opt.textContent=lmtCls[0];
                                cardIdSel.append(opt);                                
                                showClsRemain([[lmtCls[0],lmtCls[1],lmtCls[2]]]);                                
                            }
                        }


                        const event=new Event('change');
                        cardIdSel.dispatchEvent(event); 

                        if(cardIdSel.value){
                            allTrainContents.style.display='block'; 
                            cardId.style.display='block';
                            errBuyType.textContent='';
                        }else{
                            allTrainContents.style.display='none'; 
                            validClassEndTime.textContent='';
                            cardId.style.display='none';
                            errBuyType.textContent='无有效课程';
                        }
                    }

                
                    
                })
                .catch(error=>{                    
                    errBuyType.textContent='会员无有效的限时课程';
                    validClassEndTime.textContent='';
                    console.error('获取目前有效限时课程错误：',error)
                });
        }

        function showClsRemain(data){
            const cardIdStr=document.getElementById("cardIdStr");
            const clsRemain=document.getElementById('clsRemain');
            clsRemain.textContent='';
            cardIdStr.addEventListener('change',function(){   
                const cardIdSel=cardIdStr.value;
                // console.log(data)
                data.forEach(item=>{
                    if(item[0]===cardIdSel){
                        clsRemain.innerHTML=` <span style='font-weight:bold;font-size:10px;'>该卡剩余${parseInt(item[2])}节</span>`
                        if(parseInt(item[2])<=5){
                            clsRemain.innerHTML=` <span style='color:#f23c1f;font-weight:bold;font-size:10px;'>该卡剩余${parseInt(item[2])}节，请提醒会员续课。</span>`
                        }
                         
                    }
                })

                

            });    
        }

        // 递归替换Undefined值为-
        function replaceUndefinedWithDash(obj) {
            for (let key in obj) {
                if (typeof obj[key] === 'object') {
                // 如果值是嵌套的字典，递归调用函数处理内部的字典
                obj[key] = replaceUndefinedWithDash(obj[key]);
                } else if (obj[key] === undefined) {
                // 如果值是 undefined，替换为 '-'
                obj[key] = '-';
                }
            }
            return obj;
            }

        function reportClassTaken(){
            data=classAndBodyHistory;
            // console.log('class and body history:',data);
            // 递归替换Undefined值为-
            data=replaceUndefinedWithDash(data);
            // console.log('cus buy and body data',data);
            let normalClassRemain;
            const cusName=document.getElementById('nameInput').value;
            const classTakenInfo=document.getElementById('cusClsTkn');
            classTakenInfo.style.display='block';
            classTakenInfo.style.borderRadius='10px';
            classTakenInfo.innerHTML=''
            // console.log('reported by Name:',cusName);
            // console.log('class taken data:',data)
            // const total_cls_tkn_qty=data['上课次数-常规课程-私教']+data['上课次数-常规课程-瑜伽']+data['上课次数-限时课程-私教']+data['上课次数-限时团课']+data['上课次数-常规团课']
            let remain_qty_cj=0;
            // let remain_qty_lmt;
            Object.keys(data).forEach(key=>{
                if(key.slice(0,9)==='剩余节数-常规课程'){
                    remain_qty_cj+=data[key]
                }
                // if(key.slice(0,8)==='剩余节数-限时课程'){
                //     remain_qty_lmt+=data[key]
                // }
            });
            // console.log('remain qty cj:',remain_qty_cj)
            let remainAlertTxt;
            if(remain_qty_cj<=5 && remain_qty_cj>0){
                remainAlertTxt=`<span style='color:#f23c1f;font-weight:bold;font-size:10px;'>&nbsp;&nbsp;  请提醒会员续课</span>`
            }else{
                remainAlertTxt=''
                remain_qty_cj=0;
            }

            // console.log('remain alert txt:',remainAlertTxt)
            
            
            try{
                if(data['会员编码及姓名']===''){
                    classTakenInfo.innerHTML='<div style="margin-top:10px;">会员有未完善的信息或没有以往上课及体测信息。</div>';
                }else{
                    if(normalClassRemain===''){
                    normalClassRemain=0;
                    }
                    let bfr
                    if(!data['msr_num']){
                        data['msr_num']='-';
                        data['lst_msr_date']='-';
                        data['wt']='-';
                        data['waist']='-';
                        data['l_leg']='-';
                        data['r_leg']='-';
                        data['hip']='-';
                        data['body_problems']='-';
                        bfr='-'
                        
                    }else{
                        // bfr=(parseFloat(data['bfr'])*100).toFixed(2)
                        bfr=isNaN(parseFloat((data['bfr']*100).toFixed(2)))?'-':(data['bfr']*100).toFixed(2);
                        if(!data['body_problems']){
                            data['body_problems']='未记录有体测问题';
                        }
                    }
                    let clsTknHtml='';
                    for(let key in data){
                        if(key.slice(0,5)==='上课次数-'){
                            if(data[key]!==0){
                                clsTknHtml=clsTknHtml+`<p style="margin-left: 25px; font-size:12px;"><span>- ${key.slice(5,).replace('-',' · ')} </span>${data[key]}  节</p>&#10; `
                            }
                            
                        }}
                    
                    clsTknHtml=clsTknHtml.trim();



                    const showDate=new Date(data['限时课程到期日']);
                    showDate.setDate(showDate.getDate()-1);

                    classTakenInfo.innerHTML=`
                            <h2 style="color:#fafafa;">以往上课及体测情况</h2>
                            <div >
                            <p><span style="font-size:12px;">· 上次上课日期：</span>${dateFormat(new Date(data['最后一次上课日期']),'date')}</p>
                            <p><span style="font-size:12px;">· 最近一次限时课程到期日：</span>${dateFormat(showDate,'date')?dateFormat(showDate,'date'):'-'}</p>
                            </div>
                            <div >
                            <p><span style="display: inline;font-size:12px;">· 常规课程剩余节数：</span>${parseInt(remain_qty_cj)} 节`+remainAlertTxt+` </p>
                            <p><span style="display: inline;font-size:12px;">· 上课频率：</span>${(parseFloat(data['上课频率'])).toFixed(2)} 次/周</p>
                            </div>
                            <hr>
                            <div >
                            <p><span style="font-size:12px;">· 上课总节数： </span>${data['上课总次数']}  节</p>`
                            +clsTknHtml
                            +
                            `</div>
                            <hr>
                            <div >
                            <p><span style="font-size:12px;">· 围度测量次数: </span>${data['msr_num']} 次</p>
                            <p><span style="font-size:12px;">· 上次围度测量时间： </span>${data['lst_msr_date']}  </p>
                            <p><span style="font-size:12px;">· 上次围度测量结果</span></p>
                            <!-- <p style="margin-left: 25px;"><span>体重： </span>xxx Kg <span  style="margin-left: 10px;">估算体脂率： </span>xxx %</p>
                            <p style="margin-left: 25px;"><span>腰围： </span>xxx cm <span  style="margin-left: 10px;">臀围： </span>xxx cm</p>
                            <p style="margin-left: 25px;"><span>左大腿围： </span>xxx cm <span  style="margin-left: 10px;">右大腿围： </span>xxx cm</p> -->
                            <table class='table' style="font-size:12px;">
                                <tr>
                                <td ><span>体重： </span>${data['wt']}  Kg</td>
                                <td ><span>估算体脂率： </span>${bfr} %</td>
                                </tr>
                                <tr>
                                <td ><span>腰围： </span>${data['waist']}   cm</td>
                                <td ><span>臀围： </span>${data['hip']}   cm</td>
                                </tr>
                                <tr>
                                <td ><span>左大腿围： </span>${data['l_leg']}   cm</td>
                                <td ><span>右大腿围： </span>${data['r_leg']}   cm</td>
                                </tr>
                            </table>
                            
                            <div style='display:flex;flex-flow:row;margin-top:12px;font-size:12px;justify-content: start;align-items: center;'>
                                <div style='display:flex;justify-content: center;align-items: center;width:80px;margin:4px;padding:3px;border-radius:4px;background-color:#913343;color:#ffffff;'>体测问题</div>
                                <div style='margin-left:5px;font-size:12px;'>${data['body_problems']}</div>
                            </div>
                            </div>
                            `       
                        classTakenInfo.style.padding="20px";    
                }
            }catch(error){
                classTakenInfo.innerHTML='<div style="margin-top:10px;">会员有未完善的信息或没有以往上课及体测信息。</div>'
                console.error('Error:',error);
            }         
            
        }


        function hideProcessingModel() {
            document.getElementById('processingModel').style.display = 'none';
        }

        function showProcessingModel() {
            document.getElementById('processingModel').style.display = 'block';
        }
   
        //递归函数，用于多层遍历
        function traverseElementsRename(element,num) {
        // 遍历当前元素的子节点
            for (let child of element.children) {
                // console.log('id,name:',child.id,child.name)
   
                ptn=/.*-\d{0,1}/;        
                if(ptn.test(child.id)){
                    child.id=child.id.slice(0,-1)+num;
                    
                }
                if(ptn.test(child.name)){
                    child.name=child.name.slice(0,-1)+num;
                    // console.log('new child.name:',child.name)
                }

                const labelFor=child.getAttribute('for');
                if(ptn.test(labelFor)){
                    child.htmlFor=child.htmlFor.slice(0,-1)+num;
                }
                // console.log('new',child.id);

                // 处理 onchange 属性
                const onchange = child.getAttribute('onchange');
                if (onchange) {
                    const updatedOnchange = onchange.replace(/\(\d+\)/g, '(' + num + ')');
                    child.setAttribute('onchange', updatedOnchange);
                }

                // 如果当前元素有子元素，则递归调用 traverseElements 函数
                if (child.children.length > 0) {
                    traverseElementsRename(child,num);
                }
                }
        }

        function hideTrainList(d){
            const showBlock=d.nextElementSibling;
            showBlock.innerHTML='';
        }

        function handleNonOxyNameInput(d){
            // 点击抗阻时，清除有氧的内容，避免同一块下有氧和无氧项目名称的拼接
            // console.log('d input:',d)
            const order=d.id.split('-')[1];
            document.getElementById('oxyName-'+order).value='';
            document.getElementById('oxyTime-'+order).value='';
            document.getElementById('oxyGroup-'+order).value=1;

            const form=document.querySelector('input[name="form-'+order+'"]:checked').value;
            const muscle=document.querySelector('input[name="muscle-'+order+'"]:checked').value;
            // console.log(selectValue);
            let trainList=[];
            Object.keys(train_list['by_action_name']).forEach(key=>{
                if(train_list['by_action_name'][key][0]===form && train_list['by_action_name'][key][1]===muscle && !trainList.includes(key)){
                    trainList.push(key)
                }
            });
           
            // console.log(showBox.id);
            const showBoxId='nonOxyTrainList-'+order;
            generateTrainList(trainList,d.id,showBoxId);
            document.getElementById('nonOxyName-'+order).addEventListener('blur',function(){
                const inputedTrainItem=document.getElementById('nonOxyName-'+order).value;
                let trainNameInListCount=0;
                //失焦时判断input框内的内容是否在给出的训练项目list内，如不在，则清空input框。
                trainList.forEach(function(trainName){
                    if(trainName===inputedTrainItem){
                        trainNameInListCount+=1;
                    }                
                });
                if(trainNameInListCount===0){
                    document.getElementById('nonOxyName-'+order).value='';
                }
            });
            
        }
            
        function handleOxyNameInput(d){
             // 点击有氧时，重置抗阻训练的内容，避免同一块下有氧和无氧项目名称的拼接
            const order=d.id.split('-')[1];
            document.getElementById('nonOxyName-'+order).value='';
            document.getElementById('nonOxyWt-'+order).value=0;
            document.getElementById('nonOxyNum-'+order).value=1;
            document.getElementById('nonOxyDis-'+order).value='';
            document.getElementById('nonOxyGroup-'+order).value=1;

            // const filterType=d.parentNode.previousElementSibling.previousElementSibling;
            const form=document.querySelector('input[name="form-'+order+'"]:checked').value;
            const muscle=document.querySelector('input[name="muscle-'+order+'"]:checked').value;
            // console.log(selectValue);
            let trainList=[];
            Object.keys(train_list['by_action_name']).forEach(key=>{
                if(train_list['by_action_name'][key][0]===form && train_list['by_action_name'][key][1]===muscle && !trainList.includes(key)){
                    trainList.push(key)
                }
            });
            
            // console.log(showBox.id);
            const showBoxId='oxyTrainList-'+order;
            const showBox=document.getElementById(showBoxId);
            generateTrainList(trainList,d.id,showBoxId);
            document.getElementById('oxyName-'+order).addEventListener('blur',function(){
                const inputedTrainItem=document.getElementById('oxyName-'+order).value;
                let trainNameInListCount=0;
                //失焦时判断input框内的内容是否在给出的训练项目list内，如不在，则清空input框。
                trainList.forEach(function(trainName){
                    if(trainName===inputedTrainItem){
                        trainNameInListCount+=1;
                    }                
                });
                if(trainNameInListCount===0){
                    document.getElementById('oxyName-'+order).value='';
                }
            });
        }

        function copyTrain(){
            copyCount+=1;
            blockOrder=blockOrder+1;
            const originalDiv=document.getElementById('trainItemDetail-0');
            const copiedDiv=originalDiv.cloneNode(true);

            // 递归函数实现id及name以及label的for标签的改名    
            traverseElementsRename(copiedDiv,(blockOrder-1));
            // copiedDiv本身的id改名
            copiedDiv.id='trainItemDetail-'+(blockOrder-1);


            copiedDiv.querySelector('#trainRecCount-'+(blockOrder-1)).textContent='训练记录 第'+(blockOrder)+'条';
         
            // 增加删除按钮
            const deleteTrain=document.createElement('button');
            deleteTrain.style.marginTop='6px';
            deleteTrain.setAttribute('id','deleteTrain-'+(blockOrder-1)); 
            deleteTrain.textContent='删除';
            deleteTrain.addEventListener('click',function(){
                deleteTrainBlock(this,parent='y');
            })

            // 从第3条开始，删除上一个输入块的删除按钮
            if(blockOrder>=3){
                const deleteTrainPrevious=document.getElementById('deleteTrain-'+(blockOrder-2));
                deleteTrainPrevious.remove();
            }

            // 调整原来的分隔线到删除按钮下
            const hrElement=copiedDiv.querySelector('hr');
            hrElement.remove();
            copiedDiv.appendChild(deleteTrain);
            const hr=document.createElement('hr');
            copiedDiv.appendChild(hr);

            // 新的copiedDiv加到下面
            originalDiv.parentNode.appendChild(copiedDiv);

            
            //初始化输入类型的选择以及相关的radio的选择
            initInputTypeAndForm((blockOrder-1));
            // 初始化有氧无氧名称为空
            document.getElementById('nonOxyName-'+(blockOrder-1)).value='';
            document.getElementById('oxyName-'+(blockOrder-1)).value='';
        }

        function initInputTypeAndForm(idNum){
            const inputTypeSel=document.getElementById('inputType-'+idNum);
            for (let i = 0; i < inputTypeSel.options.length; i++) {
                    if (inputTypeSel.options[i].value === '分类输入') {
                        inputTypeSel.options[i].selected = true;
                        const event=new Event('change');
                        inputTypeSel.dispatchEvent(event);
                        break;
                    }
                }
            const formRadios = document.querySelectorAll('input[name="form-'+idNum+'"]'); 
            for (const radio of formRadios) {
                // console.log(radio.value);
                if (radio.value === '抗阻训练') {
                    radio.checked = true;
                    const event=new Event('change');
                    radio.dispatchEvent(event);
                    break;
                }
            }
        }

        function deleteTrainBlock(blk,parent){
            let deleteBlock;
            deleteCount+=1;
            blockOrder=blockOrder-1;
            if(parent==='y'){
                deleteBlock=blk.parentNode;
            }else{
                deleteBlock=blk;
            }
            
            // const previousTrainBlock=buttonDeleteTrain.previousElementSibling;
            const previousTrainBlock=document.getElementById('trainItemDetail-'+(parseInt(blk.id.slice(-1))-1))
            

            if(blockOrder>=2){
                
                const deleteTrain=document.createElement('button');
                deleteTrain.setAttribute('id','deleteTrain-'+(blockOrder-1)); 
                deleteTrain.textContent='删除';
                deleteTrain.addEventListener('click',function(){
                    deleteTrainBlock(previousTrainBlock,parent='n');
                })
                const hrElement=previousTrainBlock.querySelector('hr');
                hrElement.remove();
                previousTrainBlock.appendChild(deleteTrain);
                const hr=document.createElement('hr');
                previousTrainBlock.appendChild(hr);
            }

            deleteBlock.remove();
            
            
        }

        function showInputDetailBox(idInput){
            // console.log('showInputDetailBox id input:',idInput)
            const id=idInput;
            const inputType=document.getElementById('inputType-'+id).value;
            let form;
            try{
                form=document.querySelector('input[name="form-'+id+'"]:checked').value;
            }catch(err){
                form='有氧训练';
                const formRadios = document.querySelectorAll('input[name="form-'+id+'"]'); 
                for (const radio of formRadios) {
                    // console.log(radio.value);
                    if (radio.value === '有氧训练') {
                        radio.checked = true;
                        const event=new Event('change');
                        radio.dispatchEvent(event);
                        break;
                    }
                }

                console.log(err);
            }
            
            const oxy=document.getElementById('oxy-'+id);
            const oxyName=document.getElementById('oxyName-'+id);
            const nonOxy=document.getElementById('nonOxy-'+id);
            const nonOxyName=document.getElementById('nonOxyName-'+id);
            oxyName.value='';
            oxyName.disabled=false;
            nonOxyName.value='';
            nonOxyName.disabled=false;

            if(inputType==='模糊输入'){
                nonOxy.style.display='none';
                oxy.style.display='none';
                const inputTrainName=document.getElementById('inputByInput-'+id).value;
                const trainList=train_list['by_action_name'];
                Object.keys(trainList).forEach(item=>{
                    if(item===inputTrainName){
                        const trainType=trainList[item][0]
                        if(trainType==='有氧训练'){
                            nonOxy.style.display='none';
                            oxyName.value=item;
                            oxyName.disabled=true;
                            oxy.style.display='block';                             
                            
                        }else{
                            nonOxy.style.display='block';
                            oxy.style.display='none';
                            nonOxyName.value=item;
                            nonOxyName.disabled=true;
                        }
                    }
                });
            }else{
                nonOxy.style.display='none';
                oxy.style.display='none';
                if(form==='有氧训练'){
                    nonOxy.style.display='none';
                    oxy.style.display='block';
                }else{
                    nonOxy.style.display='block';
                    oxy.style.display='none';
                }
            }           
           
        }

        function handleTrainNameInput(idInput){
            const id=idInput.split('-')[1];
            try{
                const oxy=document.getElementById('oxy-'+id);
                const nonOxy=document.getElementById('nonOxy-'+id);
                const oxyName=document.getElementById('oxyName-'+id);
                const nonOxyName=document.getElementById('nonOxyName-'+id);
                oxyName.value='';
                oxyName.disabled=false;
                nonOxyName.value='';
                nonOxyName.disabled=false;
                oxy.style.display='none';
                nonOxy.style.display='none';
            }
            catch(error){
                console.log(error)
            }



            
            // console.log('handleTrainNameInput id input:',idInput,id)
            const trainNameInput=document.getElementById(idInput);
            // 获取输入框中的值
            const searchTerm = document.getElementById(idInput).value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("inputByInputTrainList-"+id);
            

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            const trainList=train_list['by_action_name'];
            // console.log('trainList:',trainList)
            // 遍历给定的数组，进行模糊匹配
            Object.keys(trainList).forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.textContent = name;

                    // 添加点击事件监听器,点击名字时执行。
                    listItem.addEventListener("click", function() {
                        // trainNameInput.textContent='';
                        // 点击后将完整的姓名设置为输入框的值
                        trainNameInput.value = name;
                        // 点击后隐藏名字列表框
                        resultList.style.display = "none";
                        showInputDetailBox(id);
                        
                    });
                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                }
            });  
        }

        function showInputBox(idInput){
            const id=idInput.split('-')[1]
            const inputType=document.getElementById('inputType-'+id).value;
            const inputByCat=document.getElementById('inputByCatBox-'+id);
            const inputByInput=document.getElementById('inputByInputBox-'+id);
            if(inputType==='分类输入'){
                inputByCat.style.display='block';
                inputByInput.style.display='none';
            }else{
                inputByCat.style.display='none';
                inputByInput.style.display='block';
            }

        }

         function initForm(data){
            const selectTrainForm=document.getElementById('formBox-0');
            const order = ["抗阻训练", "有氧训练", "综合训练", "伸展拉伸"];

            const formKeys=Object.keys(data['by_form']).sort(function(a, b) {
            return order.indexOf(a) - order.indexOf(b);
            });

            const id='0';

            let firstRadio=true;
            
            formKeys.forEach(item=>{
                const radioInput = document.createElement("input");
                radioInput.setAttribute('id',item+"-"+id);
                radioInput.setAttribute("type", "radio");
                radioInput.setAttribute("name", "form-0");        
                radioInput.setAttribute("value", item);
                // radioInput.setAttribute("class","dynamic-radio");
                radioInput.setAttribute("onchange", "generateMuscle("+id+");showInputDetailBox("+id+");clearTrainItemInput("+id+");");
                
                if(firstRadio){    
                    radioInput.checked=true;
                    firstRadio=false;
                }
                
                // 创建一个label元素，并设置其内容为选项文字
                const label = document.createElement("label");
                label.textContent = item;
                label.setAttribute('for',item+"-"+id);
                
                // 将radio和label元素添加到容器中
                selectTrainForm.appendChild(radioInput);
                selectTrainForm.appendChild(label);
            });
            initAction();
        }

        function initMuscle(data){
            const selectTrainMuscle=document.getElementById('muscleBox-0');
            
            let radios = []; // 存储生成的 radio 元素
            let extraMuscles = []; // 存储超出 order 长度的 radio 元素
            let firstRadio=true;
            Object.keys(data['by_muscle']).forEach(item=>{
                let muscleArr=[]
                data['by_muscle'][item].forEach(opt=>{
                    if(opt[0]==='抗阻训练' && !muscleArr.includes(item)){
                        const radioInput = document.createElement("input");
                        radioInput.setAttribute('id',item+"-0");
                        radioInput.setAttribute("type", "radio");
                        radioInput.setAttribute("name", "muscle-0");        
                        radioInput.setAttribute("value", item);
                        radioInput.setAttribute("class","dynamic-radio");
                        radioInput.setAttribute("onchange", "showInputDetailBox(0);clearTrainItemInput(0);");
                        
                        if(firstRadio){    
                            radioInput.checked=true;
                            firstRadio=false;
                        }
                        
                        // 创建一个 label 元素，并设置其内容为选项文字
                        const label = document.createElement("label");
                        label.textContent = item;
                        label.setAttribute('for', item + "-0");

                        // 将 radio 元素存储在 radios 数组中
                        radios.push({ radio: radioInput, label: label });
                        muscleArr.push(item);
                        
                        // 将radio和label元素添加到容器中
                        // selectTrainMuscle.appendChild(radioInput);
                        // selectTrainMuscle.appendChild(label);

                    }
                });
                
                
            });

            // 按照 order 顺序排列 radio 元素
            const order=['上肢肌群','下肢肌群','背部肌群','胸部肌群','核心肌群','复合肌群'];
            radios.sort((a, b) => {
                return order.indexOf(a.label.textContent) - order.indexOf(b.label.textContent);
            });

            // 将超出 order 长度的 radio 元素存储在 extraMuscles 数组中
            if (radios.length > order.length) {
                extraMuscles = radios.slice(order.length);
                radios = radios.slice(0, order.length);
            }

            // 清空 selectTrainMuscle
            selectTrainMuscle.innerHTML = '';

            // 将排序后的 radio 元素添加到 selectTrainMuscle 中，每添加 4 个元素就换行显示
            let counter = 0;
            radios.forEach(radio => {
                selectTrainMuscle.appendChild(radio.radio);
                selectTrainMuscle.appendChild(radio.label);
                counter++;
                if (counter % 4 === 0) {
                    selectTrainMuscle.appendChild(document.createElement("br"));
                    selectTrainMuscle.appendChild(document.createElement("br"));
                }
            });

            // 将多出的 radio 元素添加到 selectTrainMuscle 中，每添加 4 个元素就换行显示
            extraMuscles.forEach(extra => {
                selectTrainMuscle.appendChild(extra.radio);
                selectTrainMuscle.appendChild(extra.label);
                counter++;
                if (counter % 4 === 0) {
                    selectTrainMuscle.appendChild(document.createElement("br"));
                    selectTrainMuscle.appendChild(document.createElement("br"));
                }
            });
        }


        function initAction(){
            const nonOxy=document.getElementById('nonOxy-0');
            nonOxy.style.display='block';
        }

        function clearTrainItemInput(id){
            const form=document.querySelector('input[name="form-'+id+'"]:checked').value;
            const muscle=document.querySelector('input[name="muscle-'+id+'"]:checked').value;
            // if(form==='有氧训练'){
            //     const inputBox=document.getElementById('oxyName-'+id)
            //     const trainResList=document.getElementById('oxyTrainList-'+id);
            //     inputBox.value='';
            //     trainResList.style.display='none';
            // }else{
            //     const inputBox=document.getElementById('nonOxyName-'+id)
            //     const trainResList=document.getElementById('nonOxyTrainList-'+id);
            //     inputBox.value='';
            //     trainResList.style.display='none';
            // }
            const inputByInput=document.getElementById('inputByInput-'+id);
            inputByInput.value='';
            const inputBoxOxy=document.getElementById('oxyName-'+id)
            const trainResListOxy=document.getElementById('oxyTrainList-'+id);
            const oxyTime=document.getElementById('oxyTime-'+id);
            inputBoxOxy.value='';
            inputBoxOxy.value='';
            oxyTime.value='';
            trainResListOxy.style.display='none';
            const inputBoxNonOxy=document.getElementById('nonOxyName-'+id)
            const trainResListNonOxy=document.getElementById('nonOxyTrainList-'+id);
            inputBoxNonOxy.value='';
            trainResListNonOxy.style.display='none';

        }

        function generateMuscle(id){
            const form = document.querySelector('input[name="form-'+id+'"]:checked').value;
            const selectTrainMuscle = document.getElementById('muscleBox-'+id);
            selectTrainMuscle.innerHTML = '';

            let firstRadio = true;
            let radios = []; // 存储生成的 radio 元素
            let extraMuscles = []; // 存储超出 order 长度的 radio 元素

            // 遍历 train_list['by_muscle'] 对象的键，生成 radio 元素
            Object.keys(train_list['by_muscle']).forEach(item => {
                let muscleArr = []
                train_list['by_muscle'][item].forEach(opt => {
                    if (opt[0] === form && !muscleArr.includes(item)) {
                        const radioInput = document.createElement("input");
                        radioInput.setAttribute('id', item + "-" + id);
                        radioInput.setAttribute("type", "radio");
                        radioInput.setAttribute("name", "muscle-" + id);
                        radioInput.setAttribute("value", item);
                        radioInput.setAttribute("class", "dynamic-radio");
                        radioInput.setAttribute("onchange", "showInputDetailBox(" + id + ");clearTrainItemInput(" + id + ");");

                        if (firstRadio) {
                            radioInput.checked = true;
                            firstRadio = false;
                        }

                        // 创建一个 label 元素，并设置其内容为选项文字
                        const label = document.createElement("label");
                        label.textContent = item;
                        label.setAttribute('for', item + "-" + id);

                        // 将 radio 元素存储在 radios 数组中
                        radios.push({ radio: radioInput, label: label });
                        muscleArr.push(item);
                    }
                });
            });

            // 按照 order 顺序排列 radio 元素
            const order=['上肢肌群','下肢肌群','背部肌群','胸部肌群','核心肌群','复合肌群'];
            radios.sort((a, b) => {
                return order.indexOf(a.label.textContent) - order.indexOf(b.label.textContent);
            });

            // 将超出 order 长度的 radio 元素存储在 extraMuscles 数组中
            if (radios.length > order.length) {
                extraMuscles = radios.slice(order.length);
                radios = radios.slice(0, order.length);
            }

            // 清空 selectTrainMuscle
            selectTrainMuscle.innerHTML = '';

            // 将排序后的 radio 元素添加到 selectTrainMuscle 中，每添加 4 个元素就换行显示
            let counter = 0;
            radios.forEach(radio => {
                selectTrainMuscle.appendChild(radio.radio);
                selectTrainMuscle.appendChild(radio.label);
                counter++;
                if (counter % 4 === 0) {
                    selectTrainMuscle.appendChild(document.createElement("br"));
                    selectTrainMuscle.appendChild(document.createElement("br"));
                }
            });

            // 将多出的 radio 元素添加到 selectTrainMuscle 中，每添加 4 个元素就换行显示
            extraMuscles.forEach(extra => {
                selectTrainMuscle.appendChild(extra.radio);
                selectTrainMuscle.appendChild(extra.label);
                counter++;
                if (counter % 4 === 0) {
                    selectTrainMuscle.appendChild(document.createElement("br"));
                    selectTrainMuscle.appendChild(document.createElement("br"));
                }
            });
        }

        //点选部位radio时的动作
        function generateTrainItem(dd){            
            const radioValue=dd.value;
            // console.log(radioValue)
            if(radioValue==="有氧训练"){
                dd.parentNode.parentNode.nextElementSibling.style.display='none';
                dd.parentNode.parentNode.nextElementSibling.nextElementSibling.style.display='block';
            }else{
                dd.parentNode.parentNode.nextElementSibling.style.display='block';
                dd.parentNode.parentNode.nextElementSibling.nextElementSibling.style.display='none';
            }
            
        }

        function clearTrainItemHistory(input_id,conserve_train_name){
            const trainItemBlock=document.getElementById(input_id);
            const trainItemParent=document.getElementById(input_id).parentNode;
            const trainItemInputs=trainItemParent.querySelectorAll('input');
            const trainItemSelects=trainItemParent.querySelectorAll('select');
            //避免在同一个项目中切换有氧及无氧时，会发生名称拼接的情况，导致反查肌肉或动作大类错误！！
            if(input_id.split('-')[0]==='oxyName'){
                document.getElementById('nonOxyName-'+input_id.split('-')[1]).value='';
            }else if(input_id.split('-')[0]==='nonOxyName'){
                document.getElementById('oxyName-'+input_id.split('-')[1]).value='';
            }
            // trainItemSelects.forEach(selectItem=>{
            //     selectItem.value='';
            // });         
        }


        function checkTrainName(input_id){
            const inputedTrainName=document.getElementById(input_id).value;

        }

        function generateTrainList(arr,input_id,show_id){
            // console.log(input_id,show_id);
            const searchTerm = document.getElementById(input_id).value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById(show_id);
            resultList.style.display='block';
            // 清空列表
            resultList.innerHTML = "";
            
            if(UpperSearchTerm===""){
                resultList.innerHTML = "";  
                arr.forEach(function(name) {                
                // 创建列表项元素，并设置其文本内容为匹配到的结果
                const listItem = document.createElement("li");
                listItem.textContent = name; 
                // 添加点击事件监听器
                listItem.addEventListener("click", function() {
                    // 点击后将完整的姓名设置为输入框的值         
                    document.getElementById(input_id).value = name;
                    //清除之前的选项，避免先选有氧又再选无氧时训练名称的拼接！！！！
                    // clearTrainItemHistory(input_id,document.getElementById(input_id).value);

                    resultList.style.display='none';
                    // 清空结果列表
                    resultList.innerHTML = "";  
                    
                });

                // 将列表项添加到结果列表中
                resultList.appendChild(listItem);
            
                });
            }else{
                arr.forEach(function(name) {
                    if (name.includes(UpperSearchTerm)) {
                        // 创建列表项元素，并设置其文本内容为匹配到的结果
                        const listItem = document.createElement("li");
                        listItem.textContent = name;

                        // 添加点击事件监听器
                        listItem.addEventListener("click", function() {
                            resultList.style.display='block';
                            // 点击后将完整的训练项目名称写入input框的值
                            document.getElementById(input_id).value = name;
                    
                            // resultList.innerHTML = "";  
                            resultList.style.display='none';
                        });

                        // 将列表项添加到结果列表中
                        resultList.appendChild(listItem);
                    }
                });
            }
        }        

        function generateBuyTypeList(data){
            let buyTypeSelect=document.getElementById('buyType')
            const buyTypes=data.cls_types;
            buyTypes.forEach(function(buyType){
                let option=document.createElement('option');
                option.value=buyType;
                option.textContent=buyType;
                buyTypeSelect.appendChild(option);
            })
        }

        function submit(){
            let insIdPage;
            if(insRole==='admin'){
                insIdPage=document.getElementById('insSelect').value;
            }else if(insRole==='ins'){
                insIdPage=insId;
            }else{
                insIdPage=insId;
            }
            const cusName=document.getElementById('nameInput').value;
            const storedClassInfo = localStorage.getItem(insIdPage+'-'+cusName+"-cls_recs");
            const clsTknDateTime=document.getElementById('datetime').value;
            // const clsTknDateTime='2024-06-06T08:07';
            const daysDiffToday=compareDatesOnly2(new Date(clsTknDateTime),new Date());
            let dateSTr='';
            if(daysDiffToday===0){
                dateSTr='【今天】'
            }
            if(daysDiffToday===1){
                dateSTr='【昨天】'
            }
            if(daysDiffToday===2){
                dateSTr='【前天】'
            }
            if(daysDiffToday>=3){
                dateSTr=`【${daysDiffToday}天前】`;
            }
            if(daysDiffToday===-1){
                dateSTr='【明天】'
            }
            if(daysDiffToday===-2){
                dateSTr='【后天】'
            }
            if(daysDiffToday<=-3){
                dateSTr=`【${daysDiffToday*-1}天后】`;
            }
            
            const confirmedDate=confirm(`请确认上课日期：${clsTknDateTime.split('T')[0]} ${dateSTr} ${clsTknDateTime.split('T')[1]}`);
            if(!confirmedDate){
                return;
            }
            // console.log(storedClassInfo);
            if (storedClassInfo) {
                dat = JSON.parse(storedClassInfo);   
                showProcessingModel();                
                // console.log(dat)
                
                fetch('/deal_cls', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body:JSON.stringify(dat)
                    })
                  .then(response => response.json())
                  .then(data => {
                    //   console.log(data);           
                    if(data['res']==='ok'){
                        localStorage.removeItem(insIdPage+'-'+dat['cls_tkn']['cus_name']+'-html-clsinput');
                        localStorage.removeItem(insIdPage+'-'+dat['cls_tkn']['cus_name']+'-cls_recs');
                        localStorage.removeItem(insIdPage+'-'+dat['cls_tkn']['cus_name']+'-copyCount');
                        localStorage.removeItem(insIdPage+'-'+dat['cls_tkn']['cus_name']+'-deleteCount');
                        localStorage.removeItem(insIdPage+'-'+dat['cls_tkn']['cus_name']+'-blockOrder');
                        hideProcessingModel();
                        alert(data['data']);
                        window.location.replace('./index');
                    }else{        
                        console.log(data.error);
                        hideProcessingModel();
                        alert('写入错误，请联系管理员。');
                        window.location.replace('./index');
                    }
                    
                  })
                  .catch(error => {
                      console.error('Error:', error);
                      alert("提交失败，请稍后再试");
                  });

            } else {
                alert("无暂存的上课及训练记录，请先暂存信息再提交");
            }
        }

        function insIdToInsName(insId){
            let insNameFromId;
            let ctn=true;
            // console.log(ins_list)
            ins_list.forEach(function(insItem){
                if(ctn){
                    if(insItem.includes(insId)){
                    insNameFromId=insItem.slice(8,);
                    ctn=false;
                    }
                }                
            })
            return insNameFromId;
        }

        function getTrainItems(){
            const trainItemsDiv=document.getElementById('trainItems');
            const trainItemsDetailDiv=document.querySelectorAll('[id*="trainItemDetail-"]');
            const trainNonOxys=trainItemsDiv.querySelectorAll('[id*="nonOxy-"]');
            const trainOxys=trainItemsDiv.querySelectorAll('[id*="Oxy-"]');

            let trainItemsAll={}
            let trainItems=[]
            trainItemsAll['trainDate']=document.getElementById('datetime').value.split("T")[0];
            trainItemsAll['calories']=document.getElementById('calories').value;
            trainItemsAll['trainComment']=document.getElementById('trainComment').value;
            for(i=0;i<trainItemsDetailDiv.length;i++){
                let trainItem={};
                const id_num=trainItemsDetailDiv[i].id.split('-')[1];  
                const inputType=document.getElementById('inputType-'+id_num).value;
                let trainType;
                let muscle;
                if(inputType==='分类输入'){
                    trainType=document.querySelector('input[name="form-'+i+'"]:checked').value;
                    muscle=document.querySelector('input[name="muscle-'+i+'"]:checked').value;
                }else{
                    trainType='';
                    muscle='';
                }               
                
                trainItem['inputType']=inputType;
                trainItem['trainType']=trainType;
                trainItem['muscle']=muscle;
                trainItem['nonOxyName']=document.getElementById('nonOxyName-'+id_num).value;
                trainItem['nonOxyWt']=document.getElementById('nonOxyWt-'+id_num).value;
                trainItem['nonOxyDis']=document.getElementById('nonOxyDis-'+id_num).value;
                trainItem['nonOxyNum']=document.getElementById('nonOxyNum-'+id_num).value;
                trainItem['nonOxyGroup']=document.getElementById('nonOxyGroup-'+id_num).value;

                trainItem['oxyName']=document.getElementById('oxyName-'+id_num).value;
                trainItem['oxyTime']=document.getElementById('oxyTime-'+id_num).value;
                trainItem['oxyGroup']=document.getElementById('oxyGroup-'+id_num).value;

                if(inputType==='分类输入'){
                    if(trainType==="有氧训练"){
                        trainItem['trainName']=trainItem['oxyName'];
                        trainItem['nonOxyName']="";
                        trainItem['nonOxyWt']="";
                        trainItem['nonOxyDis']="";
                        trainItem['nonOxyNum']="";
                        trainItem['nonOxyGroup']="";
                    }else{
                        trainItem['trainName']=trainItem['nonOxyName'];
                        trainItem['oxyName']="";
                        trainItem['oxyTime']="";
                        trainItem['oxyGroup']="";
                    }
                }else{
                    try{
                        trainItem['trainName']=trainItem['oxyName'];
                        trainItem['trainName']=trainItem['nonOxyName'];
                    }catch(err){
                        console.log(err);
                    }
                    
                }
                
                
                trainItems.push(trainItem);
            };
            trainItemsAll['train_recs']=trainItems;

            // console.log(trainItemsAll);
            return trainItemsAll;



        }

        // 保存数据
        function tempSave(show='yes') {   
            // 将会员信息保存到本地
            const currentTime=new Date();
            const currentTimeStr=dateToString(currentTime,'dateTime');
            let insIdPage;
            let insNamePage;
            if(insRole==='admin'){
                insIdPage=document.getElementById('insSelect').value;
                insNamePage=insIdToInsName(insIdPage);
            }else if(insRole==='ins'){
                insIdPage=insId;
                insNamePage=insIdToInsName(insIdPage);
            }else{
                insIdPage=insId;
                insNamePage=insIdToInsName(insIdPage);
            }

            console.log('折算课时数cls_long:',document.getElementById('clsLong').value);
            const clsLong=document.getElementById('clsLong').value;

            const cls_tkn = {
                'cus_name':document.getElementById('nameInput').value,
                // 'sex':document.querySelector('input[name="gender"]:checked').value,
                'cls_tkn_date':document.getElementById('datetime').value.split("T")[0],
                'cls_tkn_time':document.getElementById('datetime').value.split("T")[1]+':00',
                'cls_long':document.getElementById('clsLong').value,
                'cls_type':document.getElementById('buyType').value,
                'cls_name':document.getElementById('buyClsName').value,
                'card_id':document.getElementById('cardIdStr').value,
                'ins_name':insNamePage,
                'ins_id':insIdPage,
                //操作者不是教练，是登录的人，是insId，不是ins_id
                'operator_id':insId,
                'operate_time':currentTimeStr,
                // 'ins_name':document.querySelector('input[name="insName"]:checked').value,
                'basic_cls_comment':document.getElementById('basic_cls_comment').value
            
            };
            console.log(cls_tkn)
            // alert('1337 card_id:'+cls_tkn['card_id'])

            const allTrainItems=getTrainItems()

            const cls_recs={
                "cls_tkn":cls_tkn,
                "train_rec":allTrainItems
            }


            localStorage.setItem(insIdPage+'-'+document.getElementById('nameInput').value+'-cls_recs', JSON.stringify(cls_recs));
            localStorage.setItem(insIdPage+'-'+document.getElementById('nameInput').value+'-html-clsinput',document.documentElement.outerHTML);
            localStorage.setItem(insIdPage+'-'+document.getElementById('nameInput').value+'-copyCount',copyCount);
            localStorage.setItem(insIdPage+'-'+document.getElementById('nameInput').value+'-deleteCount',deleteCount);
            localStorage.setItem(insIdPage+'-'+document.getElementById('nameInput').value+'-blockOrder',blockOrder);
            // let copyCount=0;
            // let deleteCount=0;
            // let blockOrder=1;
            
            
            // 保存完成后，遍历结果，如没有空项，禁用输入框，并显示返回修改按钮。如有，提示，不进行操作。
            let checkValueEmpty=0;
            let emptyItem='';
            for(const key in cls_recs['cls_tkn']){
                //不是备注的基础信息不能为空
                if(key!=='basic_cls_comment' && cls_recs['cls_tkn'][key]===''){
                    checkValueEmpty+=1;
                    emptyItem=emptyItem+'上课基本信息';
                }
            }

            for(const key in cls_recs['train_rec']){
                //不是备注的基础信息不能为空
                if(key==='calories' && cls_recs['train_rec'][key]===''){
                    checkValueEmpty+=1;
                    emptyItem=emptyItem+'，'+'消耗热量未填写';
                }

                //热量消耗必须为正数
                if(key==='calories' && parseInt(cls_recs['train_rec'][key])<0){
                    checkValueEmpty+=1;
                    emptyItem=emptyItem+'，'+'消耗热量为负数';
                }
            }
            

            let num=1;
            for(const key in cls_recs['train_rec']['train_recs']){
                //不是备注的基础信息不能为空
                
                if(cls_recs['train_rec']['train_recs'][key]['nonOxyName']==='' && 
                    cls_recs['train_rec']['train_recs'][key]['oxyName']==='' ){
                    checkValueEmpty+=1;
                    emptyItem=emptyItem+'，'+`第${num}条：训练项目名称`;
                }

                // 有氧训练必须有时间
                if(cls_recs['train_rec']['train_recs'][key]['oxyName']!=='' && cls_recs['train_rec']['train_recs'][key]['oxyTime']==='' ){
                    checkValueEmpty+=1;
                    emptyItem=emptyItem+'，'+`第${num}条：有氧训练时间`;
                }

                //有氧训练时间必须为正数
                if(cls_recs['train_rec']['train_recs'][key]['oxyName']!=='' && parseInt(cls_recs['train_rec']['train_recs'][key]['oxyTime'])<0){
                    checkValueEmpty+=1;
                    emptyItem=emptyItem+'，'+`第${num}条：有氧训练时间为负数`;
                }

                //抗阻训练距离必须为正数
                if(cls_recs['train_rec']['train_recs'][key]['nonOxyDis']!=='' && parseInt(cls_recs['train_rec']['train_recs'][key]['nonOxyDis'])<0){
                    checkValueEmpty+=1;
                    emptyItem=emptyItem+'，'+`第${num}条：抗阻训练距离为负数`;
                }

                


                num+=1;

                
                
            }

            
            //检查的项目不为空时，则执行。
            if(checkValueEmpty===0){
            
                document.getElementById("nameInput").setAttribute("disabled", true);
                document.getElementById('trainComment').setAttribute("disabled", true);
                document.getElementById('basic_cls_comment').setAttribute("disabled", true);

                const inputItems = document.querySelectorAll('input');
                inputItems.forEach(function(inputItem){
                    inputItem.disabled=true;
                })

                const selectItems = document.querySelectorAll('select');
                selectItems.forEach(function(selectItem){
                    selectItem.disabled=true;
                })

                const deleteButtons=document.querySelectorAll('[id*="deleteTrain-"]')
                deleteButtons.forEach(deleteButton=>{
                    deleteButton.style.display='none';
                })

                const selects1 = document.querySelectorAll('[id*="itemSelectRadio-"]');
                selects1.forEach(function(select){
                    select.style.display='none';
                })

                const selects2 = document.querySelectorAll('[id*="oxyGroup-"]');
                selects2.forEach(function(select){
                    select.disabled=true;
                })

                const selects3 = document.querySelectorAll('[id*="nonOxyGroup-"]');
                selects3.forEach(function(select){
                    select.disabled=true;
                })

                const selects4 = document.querySelectorAll('[id*="nonOxyWt-"]');
                selects4.forEach(function(select){
                    select.disabled=true;
                })

                const selects5 = document.querySelectorAll('[id*="nonOxyNum-"]');
                selects5.forEach(function(select){
                    select.disabled=true;
                })

                const deleteTrainButtons=document.querySelectorAll('[id*="deleteTrain-"]');
                deleteButtons.forEach(deleteButton=>{
                    deleteButton.disabled=true;
                })

                //隐藏训练方式选择框及输入框
                const inputTypeSels=document.querySelectorAll('[id*="inputTypeBox-"]')
                inputTypeSels.forEach(inputTypeSel=>{
                    inputTypeSel.style.display='none';
                })
                try{
                    const inputByCatBoxes=document.querySelectorAll('[id*="inputByCatBox-"]')
                    inputByCatBoxes.forEach(inputByCatBox=>{
                        inputByCatBox.style.display='none';
                    })

                    const inputByInputBoxes=document.querySelectorAll('[id*="inputByInputBox-"]')
                    inputByInputBoxes.forEach(inputByInputBox=>{
                        inputByInputBox.style.display='none';
                    })
                }catch(err){
                    console.log(err);
                }
                
                


                document.getElementById('appendTrainButton').disabled=true;

                document.getElementById('buyType').disabled=true;
                document.getElementById('clsLong').disabled=true;

                document.getElementById("tempSaveButton").style.display = "none";
                document.getElementById("editButton").style.display = "inline";
                document.getElementById("submit").style.display = "inline";
                document.getElementById("submit").disabled=false;

                if(show==='yes'){
                    alert("上课及训练记录已暂存");
                }
            }else{
                document.getElementById("submit").style.display = "none";
                document.getElementById("submit").disabled=true;
                alert(`有些信息未填写或填写错误，请检查: ${emptyItem.slice(1,)}`);
            }

        }
   
        // 修改数据
        function enableEdit() {
            // 移除禁用属性，并显示保存按钮
            // document.getElementById("nameInput").removeAttribute("disabled");
            const inputItems = document.querySelectorAll('input');
            inputItems.forEach(function(inputItem){
                inputItem.disabled=false;
            })

            const selectItems = document.querySelectorAll('select');
                selectItems.forEach(function(selectItem){
                    selectItem.disabled=false;
                })

            const deleteButtons=document.querySelectorAll('[id*="deleteTrain-"]')
            deleteButtons.forEach(deleteButton=>{
                deleteButton.style.display='block';
            })

            const selects1 = document.querySelectorAll('[id*="itemSelectRadio-"]');
            selects1.forEach(function(select){
                select.style.display='block';
            })

            const selects2 = document.querySelectorAll('[id*="oxyGroup-"]');
            selects2.forEach(function(select){
                select.disabled=false;
            })

            const selects3 = document.querySelectorAll('[id*="nonOxyGroup-"]');
            selects3.forEach(function(select){
                select.disabled=false;
            })

            const selects4 = document.querySelectorAll('[id*="nonOxyWt-"]');
            selects4.forEach(function(select){
                select.disabled=false;
            })

            const selects5 = document.querySelectorAll('[id*="nonOxyNum-"]');
            selects5.forEach(function(select){
                select.disabled=false;
            })


            const deleteTrainButtons=document.querySelectorAll('[id*="deleteTrain-"]');
            deleteButtons.forEach(deleteButton=>{
                deleteButton.disabled=false;
            })

            //显示训练方式选择框及输入框
            const inputTypeSels=document.querySelectorAll('[id*="inputTypeBox-"]')
            inputTypeSels.forEach(inputTypeSel=>{
                inputTypeSel.style.display='flex';                    
            })
            
            const trainItems=document.querySelectorAll('[id*="trainItemDetail-"]');
            for(i=0;i<trainItems.length;i++){
                const inputType=document.getElementById('inputType-'+i);
                if(inputType.value==='分类输入'){
                    const inputByCatBox=document.getElementById('inputByCatBox-'+i)
                    inputByCatBox.style.display='flex';    
                }
                if(inputType.value==='模糊输入'){                    
                    const inputByInputBox=document.getElementById('inputByInputBox-'+i)
                    inputByInputBox.style.display='flex';   
                    inputByInputBox.getElementsByTagName('div')[0].style.width='100%';
                    try{
                        const oxyName=document.getElementById('oxyName-'+i);
                        oxyName.disabled=true;
                        const nonOxyName=document.getElementById('nonOxyName-'+i);
                        nonOxyName.disabled=true;
                    }catch(err){
                        console.log(err);
                    }
                    
                }
            }

            document.getElementById('appendTrainButton').disabled=false;
            document.getElementById('trainComment').disabled=false;
            document.getElementById('basic_cls_comment').disabled=false;

            document.getElementById('buyType').disabled=false;
            document.getElementById('clsLong').disabled=false;

            document.getElementById("tempSaveButton").style.display = "inline";
            document.getElementById("editButton").style.display = "none";
            document.getElementById("submit").style.display = "none";
        }
 
        function reFillTempSave(dataString){
            let insIdPage;
            if(insRole==='admin'){
                insIdPage=document.getElementById('insSelect').value;
            }else if(insRole==='ins'){
                insIdPage=insId;
            }else{
                insIdPage=insId;
            }

            const trainSummary=document.getElementById('trainSummary');
            trainSummary.textContent='';
            
            const data=JSON.parse(dataString);
            // console.log(data);
            const cusName=document.getElementById('nameInput').value = data['cls_tkn']['cus_name'];
            copyCount=parseInt(localStorage.getItem(insIdPage+'-'+cusName+'-copyCount'));
            deleteCount=parseInt(localStorage.getItem(insIdPage+'-'+cusName+'-deleteCount'));
            blockOrder=parseInt(localStorage.getItem(insIdPage+'-'+cusName+'-blockOrder'));

            // console.log(insIdPage+'-'+cusName+'-blockOrder')

            if(blockOrder>=2){
                const deleteButton=document.getElementById('deleteTrain-'+(blockOrder-1));
                deleteButton.addEventListener('click',function(){
                    deleteTrainBlock(this,'y');
                });
            }


            document.getElementById('datetime').value = data['cls_tkn']['cls_tkn_date'] + 'T' + data['cls_tkn']['cls_tkn_time'];
            document.getElementById('clsLong').value = data['cls_tkn']['cls_long'];

            // const insRadios = document.querySelectorAll('input[name="insName"]');
            // for (const radio of insRadios) {
            //     if (radio.value === data['cls_tkn']['ins_name']) {
            //         radio.checked = true;
            //         break;
            //     }
            // }


                

            //由radio改为select
            if(insRole==='admin'){
                document.getElementById('insSelect').value=data['cls_tkn']['ins_id'];               

            }
            //读取暂存的insid
            insIdReload=data['cls_tkn']['ins_id'];

            document.getElementById('basic_cls_comment').value = data['cls_tkn']['basic_cls_comment'];
            document.getElementById('buyType').value = data['cls_tkn']['cls_type'];
            document.getElementById('buyClsName').value=data['cls_tkn']['cls_name'];
            document.getElementById('cardId').value = data['cls_tkn']['cardId'];
            

            // 回写之前的训练选项
            // train_list
            document.getElementById('calories').value = data['train_rec']['calories'];
            document.getElementById('trainComment').value = data['train_rec']['trainComment'];

            
            const trainRecs = data['train_rec']['train_recs'];

            for (let i = 0; i < trainRecs.length; i++) {
                const trainRec = trainRecs[i];
                const inputTypeSel=document.getElementById('inputType-'+i);
                for (let i = 0; i < inputTypeSel.options.length; i++) {
                    if (inputTypeSel.options[i].value === trainRec['inputType']) {
                        inputTypeSel.options[i].selected = true;
                        break;
                    }
                }


                if(trainRec['inputType']==='分类输入'){
                    const formRadios = document.querySelectorAll('input[name="form-'+i+'"]'); 
                    for (const radio of formRadios) {
                        // console.log(radio.value);
                        if (radio.value === trainRec['trainType']) {
                            radio.checked = true;
                            break;
                        }
                    }
                    const muscleRadios = document.querySelectorAll('input[name="muscle-'+i+'"]'); 
                    for (const radio of muscleRadios) {
                        // console.log(radio.value);
                        if (radio.value === trainRec['muscle']) {
                            radio.checked = true;
                            break;
                        }
                    }

                }else{
                    const inputByInput=document.getElementById('inputByInput-'+i);
                    inputByInput.value=trainRec['trainName'];
                }
                document.getElementById('nonOxyName-'+i).value=trainRec['nonOxyName'];
                document.getElementById('nonOxyWt-'+i).value=trainRec['nonOxyWt'];
                document.getElementById('nonOxyDis-'+i).value=trainRec['nonOxyDis'];
                document.getElementById('nonOxyNum-'+i).value=trainRec['nonOxyNum'];
                document.getElementById('nonOxyGroup-'+i).value=trainRec['nonOxyGroup'];
                document.getElementById('oxyName-'+i).value=trainRec['oxyName'];
                document.getElementById('oxyTime-'+i).value=trainRec['oxyTime'];
                document.getElementById('oxyGroup-'+i).value=trainRec['oxyGroup'];

                //处理回写时，抗阻训练的重量、次数、组数为空的情况
                if(document.getElementById('nonOxyName-'+i).value===''){
                    document.getElementById('nonOxyWt-'+i).value=0;
                    document.getElementById('nonOxyNum-'+i).value=1;
                    document.getElementById('nonOxyGroup-'+i).value=1;
                }
                //处理回写时，抗阻训练的重量、次数、组数为空的情况
                if(document.getElementById('oxyName-'+i).value===''){
                    document.getElementById('oxyGroup-'+i).value=1;
                }

                //通过训练名称映射训练部位或名称并选择
                if (trainRec['nonOxyName']) {
                    const trainItemRadios = document.querySelectorAll('input[name="trainItem-'+i+'"]'); 
                    for (const radio of trainItemRadios) {
                        // console.log(radio.value);
                        if (radio.value === train_list['by_action_name'][trainRec['nonOxyName']][1] || radio.value === train_list['by_action_name'][trainRec['nonOxyName']][2]) {
                            radio.checked = true;
                            break;
                        }
                    }
                } else if (trainRec['oxyName']) {                    
                    const trainItemRadios = document.querySelectorAll('input[name="trainItem-'+i+'"]'); 
                    for (const radio of trainItemRadios) {
                        // console.log(radio.value);
                        if (radio.value === train_list['by_action_name'][trainRec['oxyName']][1] || radio.value === train_list['by_action_name'][trainRec['oxyName']][2]) {
                            radio.checked = true;
                            break;
                        }
                    }
                }

            }
        

        }
        

       
    </script>
</body>
</html>
